package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/08/26 11:16
 *
 * @author ciggar
 *
 * 转账案例
 */
public class TransferDemo {

    public static void main(String[] args) throws SQLException {

        Boolean ret = transfer("风华哥", "天明", 1000);


        if (ret) {

            System.out.println("转账成功！！");
        }else {
            System.out.println("转账失败！！");
        }

    }



    // 转账的方法
    /**
     * 创建日期：2022/08/26 11:17
     * @param fromName  转账发起人
     * @param toName    转账收益人
     * @param money     转账金额
     * @return java.lang.Boolean
     * @author ciggar
     */
    public static Boolean transfer(String fromName,String toName,Integer money) throws SQLException {

        Connection connection = JDBCUtils.getConnection();

        // 开启事务
        connection.setAutoCommit(false);

        try {

            // 给指定的账户扣钱
            PreparedStatement decreaseStatement = connection.prepareStatement("update account set money = money - ? where name = ? and money >= ?");

            decreaseStatement.setInt(1, money);
            decreaseStatement.setString(2, fromName);
            decreaseStatement.setInt(3, money);

            int affectedRows = decreaseStatement.executeUpdate();

            if (affectedRows > 0) {
                System.out.println("扣钱成功！");
            } else {
                throw new RuntimeException("扣钱失败！");
            }
            decreaseStatement.close();


            int i = 1 / 0;


            // 给指定的账户加钱
            PreparedStatement addStatement = connection.prepareStatement("update account set money = money + ? where name = ?");

            addStatement.setInt(1, money);
            addStatement.setString(2, toName);

            int affectedRows2 = addStatement.executeUpdate();
            if (affectedRows2 > 0) {
                System.out.println("加钱成功！");
            } else {
                throw new RuntimeException("加钱失败！");
            }



        }catch (Exception ex) {
            ex.printStackTrace();
            // 回滚
            connection.rollback();
            return false;
        }
        connection.commit();
        return true;

    }



}
